<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageAppointmentService;
use plugin\ycMassage\app\model\MassageOrders;
use plugin\ycMassage\app\model\MassageOrdersAddress;
use plugin\ycMassage\app\model\MassageOrdersRefund;
use plugin\ycMassage\app\model\MassageOrdersSub;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\utils\enum\ActionIdentity;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\OrdersState;
use plugin\ycMassage\utils\enum\OrdersType;
use plugin\ycMassage\utils\enum\PayType;
use plugin\ycMassage\utils\enum\ServiceState;
use plugin\ycMassage\utils\notice\Notice;
use think\facade\Db;
use think\Request;

class OrdersRefundController extends BaseController
{
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->checkboxConfig();
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('trade', 'input', '订单号');
        $builder->addScreen('name', 'input', '下单人');
        $builder->addScreen('mobile', 'input', '下单手机号');
        $builder->addScreen('technician', 'input', '技师');
        $builder->addScreen('examine', 'select', '审核状态', [
            'options' => Examine::getOptions()
        ]);
        $builder->addScreen('start_time', 'input', '开始时间', [
            'type' => 'date'
        ]);
        $builder->addScreen('end_time', 'input', '结束时间', [
            'type' => 'date'
        ]);
        $builder->addRightButton('refund', '退款', [
            'api'    => $this->pluginPrefix . '/admin/OrdersRefund/refund',
            'path' => '/OrdersRefund/refund',
            'type'      => 'modal',
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => Examine::WAIT['value']
            ]
        ], [], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->addRightButton('reject', '驳回', [
            'api'    => $this->pluginPrefix . '/admin/OrdersRefund/reject',
            'path' => '/OrdersRefund/reject',
            'type'      => 'modal',
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => Examine::WAIT['value']
            ]
        ], [], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90,
            'type' => 'checkbox'
        ])
            ->addColumn('title', '服务项目详情', [
                'minWidth' => 200,
            ])
            ->addColumn('name', '下单人', [
                'width' => 160,
            ])
            ->addColumn('mobile', '下单手机号', [
                'width' => 160,
            ])
            ->addColumn('technician_nickname', '技师', [
                'width' => 160,
            ])
            ->addColumn('price', '已退款金额', [
                'width' => 100,
            ])
            ->addColumn('origin_price', '原价', [
                'width' => 100,
            ])
            ->addColumn('orders_price', '实付', [
                'width' => 100,
            ])
            ->addColumn('basic_price', '服务价', [
                'width' => 100,
            ])
            ->addColumn('overtime_price', '加钟价', [
                'width' => 100,
            ])
            ->addColumn('travel_price', '出行费', [
                'width' => 100,
            ])
            ->addColumn('material_price', '材料费', [
                'width' => 100,
            ])
            ->addColumn('coupon_money', '优惠', [
                'width' => 100,
            ])
            ->addColumn('num', '服务数量', [
                'width' => 100,
            ])
            ->addColumn('trade', '订单号', [
                'minWidth' => 200,
            ])
            ->addColumnEle('pay_type', '支付方式', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => PayType::dictOptions(),
                ],
            ])
            ->addColumn('pay_time', '支付时间', [
                'width' => 160,
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => OrdersState::dictOptions(),
                    'style' => OrdersState::dictOptions('style'),
                ],
            ])
            ->addColumn('remark', '备注', [
                'width' => 160,
            ])
            ->addColumn('create_time', '下单时间', [
                'width' => 160,
            ])
            ->addColumnEle('examine', '审核', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => Examine::dictOptions(),
                    'style' => Examine::dictOptions('style')
                ],
            ])
            ->addColumn('refund_message', '退款理由', [
                'width' => 160,
            ])
            ->addColumn('refund_time', '退款时间', [
                'width' => 160,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['o.saas_appid', '=', $request->saas_appid]
        ];
        $trade = $request->get('trade');
        if ($trade) {
            $where[] = ['o.trade', 'like', '%' . $trade . '%'];
        }
        $uid = $request->get('uid');
        if ($uid) {
            $where[] = ['o.uid', '=', $uid];
        }
        $examine = $request->get('examine');
        if ($examine !== null) {
            $where[] = ['r.examine', '=', $examine];
        }
        $start_time = $request->get('start_time');
        if ($start_time) {
            $where[] = ['o.create_time', '>=', $start_time . ' 00:00:00'];
        }
        $end_time = $request->get('end_time');
        if ($end_time) {
            $where[] = ['o.create_time', '<=', $end_time . ' 23:59:59'];
        }
        $use_role=$request->use_role;
        if ($use_role) {
            $where[] = ['r.use_role', '=', $use_role];
        }else{
            $where[] = ['r.use_role', '=', ActionIdentity::USER['value']];
        }
        $filed = [
            'r.price',
            'o.title,o.origin_price,o.price as orders_price,o.basic_price,o.overtime_price,o.travel_price,o.material_price,o.coupon_money,o.num,o.trade,o.pay_type,o.pay_time,o.state,o.remark,o.create_time',
            'r.id,r.refund_message,r.examine,r.create_time as refund_time',
        ];
        $MassageOrdersObj = MassageOrdersRefund::alias('r')->where($where);
        $MassageOrdersObj->join('massage_orders o', 'o.id = r.orders_id');
        $filed[] = 'address.name,address.mobile';
        $filed[] = 'ut.nickname as technician_nickname';
        $technician = $request->get('technician');
        if ($technician) {
            $where[] = ['t.name|t.mobile', 'like', "%{$technician}%"];
            $MassageOrdersObj->join('MassageUserTechnician t', 't.uid=o.alias_id');
        }
        $MassageOrdersObj->join('MassageUser ut', 'ut.id=o.alias_id');
        $name = $request->get('name');
        if ($name) {
            $where[] = ['address.name', 'like', "%{$name}%"];
        }
        $mobile = $request->get('mobile');
        if ($mobile) {
            $where[] = ['address.mobile', 'like', "%{$mobile}%"];
        }
        $MassageOrdersObj->join('MassageOrdersAddress address', 'address.orders_id = o.id');
        $data = $MassageOrdersObj->order('r.id desc')
            ->field($filed)
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->technician_nickname) {
                    $item->technician_nickname = base64_decode($item->technician_nickname);
                }
            });
        return $this->successRes($data);
    }
    public function technicianGetTable(Request $request){
        return $this->indexGetTable($request);
    }
    public function technician(Request $request)
    {
        $request->use_role = ActionIdentity::TECHNICIAN['value'];
        return $this->index($request);
    }
    public function refund(Request $request)
    {
        $id = $request->get('id');
        $MassageOrdersRefund = MassageOrdersRefund::where(['id' => $id, 'saas_appid' => $request->saas_appid, 'examine' => Examine::WAIT['value']])->find();
        if (!$MassageOrdersRefund) {
            return $this->fail('数据不存在');
        }
        $MassageOrders = MassageOrders::where(['id' => $MassageOrdersRefund->orders_id])->find();
        if ($request->method() === 'POST') {
            $D = $request->post();
            $MassageOrdersRefund->examine = Examine::YES['value'];
            $MassageOrdersRefund->examine_message = $D['examine_message'];
            Db::startTrans();
            try {
                /* 退款业务 */
                MassageOrders::refund($MassageOrders->id, $MassageOrdersRefund, [
                    'money' => $D['money'],
                    'service' => $D['service'] / 100,
                    'travel' => $D['travel'] / 100,
                    'refund_desc' => $D['refund_desc']
                ]);
                /* 退款业务 */
                $MassageOrdersRefund->save();
                $notice = new Notice();
                $MassageUser = MassageUser::alias('u')->where(['u.id' => $MassageOrders->uid])
                    ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                    ->field('u.nickname,u.mobile,uw.openid')
                    ->find();
                if ($MassageUser) {
                    $notice->addUSER($MassageUser->mobile, $MassageUser->openid);
                }
                $MassageUserT = MassageUser::alias('u')->where(['u.id' => $MassageOrders->alias_id])
                    ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                    ->field('u.nickname,u.mobile,uw.openid')
                    ->find();
                if ($MassageUserT) {
                    $notice->addTECHNICIAN($MassageUserT->mobile, $MassageUserT->openid);
                }
                $MassageOrdersAddress = MassageOrdersAddress::where(['orders_id' => $MassageOrders->id])->find();
                $notice->saas_appid = $MassageOrders->saas_appid;
                $notice->type = NoticeType::REFUND['value'];
                $notice->setData([
                    'trade' => $MassageOrders->trade,
                    'price' => $MassageOrders->price,
                    'refund_price' => $MassageOrdersRefund->price,
                    'time' => date('Y-m-d H:i:s'),
                    'name' => $MassageOrdersAddress['name'] . '(' . $MassageOrders->uid . ')',
                ]);
                $notice->send();
                Db::commit();
                return $this->success('审核成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }
        switch ($MassageOrders->orders_type) {
            case OrdersType::RESERVATION['value']:
                $MassageAppointmentService = MassageAppointmentService::where(['orders_id' => $MassageOrdersRefund->orders_id])->order('state desc')->find();
                break;
            case OrdersType::OVERTIME['value']:
                $MassageOrdersSub = MassageOrdersSub::where(['orders_id' => $MassageOrdersRefund->orders_id])->find();
                $MassageAppointmentService = MassageAppointmentService::where(['id' => $MassageOrdersSub->appointment_service_id])->order('state desc')->find();
                break;
        }
        $TechnicianState = [
            'type' => 'error',
            'text' => ServiceState::getText($MassageAppointmentService->state)['text']
        ];
        $travel = 100;
        if ($MassageAppointmentService->state >= ServiceState::TRAVELING['value']) {
            $travel = 50;
        }
        $service = 100;
        if ($MassageAppointmentService->state >= ServiceState::ARRIVAL['value']) {
            $service = 50;
            $travel = 0;
        }
        $MassageOrdersSub = MassageOrdersSub::alias('os')->where(['os.orders_id' => $MassageOrdersRefund->orders_id])
            ->join('MassageService s', 's.id = os.service_id')
            ->field('os.*,s.title,s.thumb')
            ->select()->each(function ($item) {
                $item->thumb = UploadService::url($item->thumb);
            });
        $overtimeOrders = MassageOrders::where(['orders_id' => $MassageOrdersRefund->orders_id])->select();
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addDivider('退款信息');
        $builder->addComponent('service', 'number', '项目退还比例(%)', $service, [
            'col'           => 6,
            'props'         => [
                'controls'      => false,
                'min'           => 0,
                'precision'     => 0,
                'max'           => 100,
            ],
        ]);
        $builder->addComponent('travel', 'number', '路费退还比例(%)', $travel, [
            'col'           => 6,
            'props'         => [
                'controls'      => false,
                'min'           => 0,
                'precision'     => 0,
                'max'           => 100,
            ],
        ]);
        $builder->addComponent('money', 'number', '自定义退款金额', 0, [
            'col'           => 6,
            'props'         => [
                'controls'      => false,
                'min'           => 0,
                'precision'     => 2,
                'max'           => $MassageOrders->price,
            ],
        ]);
        $builder->addRow('examine_message', 'textarea', '审核结果', '', [
            'col' => 12,
        ]);
        $builder->addRow('refund_desc', 'textarea', '退款原因(可选)', '', [
            'col' => 12,
        ]);
        $builder->addDivider('服务');
        $builder->addComponent('TechnicianState', 'el-tag', '服务状态', '', [
            'col'           => 6,
            'props'         => [
                'type'      => $TechnicianState['type']
            ],
            'children'      => [
                $TechnicianState['text']
            ]
        ]);
        $builder->addComponent('price', 'el-tag', '订单金额', '', [
            'col'           => 6,
            'props'         => [
                'type'      => 'success'
            ],
            'children'      => [
                "￥{$MassageOrders->price}"
            ]
        ]);
        $builder->addComponent('travel_price', 'el-tag', '路费', '', [
            'col'           => 6,
            'props'         => [
                'type'      => 'success'
            ],
            'children'      => [
                "￥{$MassageOrders->travel_price}"
            ]
        ]);
        if (!$overtimeOrders->isEmpty()) {
            $builder->addDivider('加钟');
            foreach ($overtimeOrders as $key => $item) {
                $builder->addComponent('overtime_num' . $item->id, 'el-tag', '序号', '', [
                    'col'           => 6,
                    'props'         => [
                        'type'      => 'danger'
                    ],
                    'children'      => [
                        "第" . ($key + 1) . "次加钟"
                    ]
                ]);
                $builder->addComponent('overtime_price' . $item->id, 'el-tag', '金额', '', [
                    'col'           => 6,
                    'props'         => [
                        'type'      => 'success'
                    ],
                    'children'      => [
                        "￥{$item->price}"
                    ]
                ]);
            }
        }
        $builder->addDivider('订单');
        foreach ($MassageOrdersSub as $item) {
            $builder->addComponent('url' . $item->id, 'el-avatar', '封面', '', [
                'col'           => 4,
                'props'         => [
                    'size'     => 50,
                    'shape' => 'square',
                    'src'      => $item->thumb,
                ],
            ]);
            $builder->addComponent('title' . $item->id, 'info', '服务项目', "{$item->title} x {$item->num}", [
                'col'           => 14,
                'props'         => []
            ]);
            $builder->addComponent('price' . $item->id, 'el-tag', '金额', '', [
                'col'           => 6,
                'props'         => [
                    'type'      => 'success'
                ],
                'children'      => [
                    "￥{$item->price}"
                ]
            ]);
        }
        if (!$overtimeOrders->isEmpty()) {
            $builder->addDivider('加钟订单');
            foreach ($overtimeOrders as $key => $overtimeOrder) {
                $overOrdersSub = MassageOrdersSub::alias('os')->where(['os.orders_id' => $overtimeOrder->id])
                    ->join('MassageService s', 's.id = os.service_id')
                    ->field('os.*,s.title,s.thumb')
                    ->select()->each(function ($item) {
                        $item->thumb = UploadService::url($item->thumb);
                    });
                foreach ($overOrdersSub as $item) {
                    $builder->addComponent('url' . $item->id, 'el-avatar', '封面', '', [
                        'col'           => 4,
                        'props'         => [
                            'size'     => 50,
                            'shape' => 'square',
                            'src'      => $item->thumb,
                        ],
                    ]);
                    $builder->addComponent('title' . $item->id, 'info', '服务项目', "{$item->title} x {$item->num}", [
                        'col'           => 14,
                        'props'         => []
                    ]);
                    $builder->addComponent('price' . $item->id, 'el-tag', '金额', '', [
                        'col'           => 6,
                        'props'         => [
                            'type'      => 'success'
                        ],
                        'children'      => [
                            "￥{$item->price}"
                        ]
                    ]);
                }
            }
        }
        $data = $builder->setData($MassageOrdersRefund)->create();
        return $this->successRes($data);
    }
    public function reject(Request $request)
    {
        $id = $request->get('id');
        $MassageOrdersRefund = MassageOrdersRefund::where(['id' => $id, 'saas_appid' => $request->saas_appid, 'examine' => Examine::WAIT['value']])->find();
        if (!$MassageOrdersRefund) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $MassageOrdersRefund->examine = Examine::NO['value'];
            $MassageOrdersRefund->examine_message = $D['examine_message'];
            Db::startTrans();
            try {
                $MassageOrders = MassageOrders::where(['id' => $MassageOrdersRefund->orders_id])->find();
                $MassageOrders->state = $MassageOrdersRefund->orders_state;
                $MassageOrders->save();
                $MassageOrdersSub = MassageOrdersSub::where(['orders_id' => $MassageOrdersRefund->orders_id, 'state' => OrdersState::REFUNDING['value']])->select();
                foreach ($MassageOrdersSub as $item) {
                    $item->state = $MassageOrdersRefund->orders_state;
                    $item->save();
                }
                $MassageOrdersRefund->save();
                $notice = new Notice();
                $MassageUser = MassageUser::alias('u')->where(['u.id' => $MassageOrders->uid])
                    ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
                    ->field('u.nickname,u.mobile,uw.openid')
                    ->find();
                if ($MassageUser) {
                    $notice->addUSER($MassageUser->mobile, $MassageUser->openid);
                }
                $notice->saas_appid = $MassageOrders->saas_appid;
                $notice->type = NoticeType::EXAMINE['value'];
                $notice->role = ['USER'];
                $notice->setData([
                    'type' => '退款申请',
                    'state' => '已驳回',
                    'result' => $MassageOrdersRefund->examine_message,
                    'trade' => $MassageOrders->trade,
                    'time' => date('Y-m-d H:i:s')
                ]);
                $notice->send();
                Db::commit();
                return $this->success('审核成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('examine_message', 'textarea', '驳回理由', '', [
            'col' => 24,
        ]);
        $data = $builder->setData($MassageOrdersRefund)->create();
        return $this->successRes($data);
    }
}
